package com.thread.basic;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**   
*    
* 项目名称：ThreadDemo   
* 类名称：ExchangerTest   
* 类描述：Exchanger用于进行线程间的数据交换。它提供一个同步点，在这个同步点两个线程可以交换彼此的数据。
* 创建人：jzhang  
* 创建时间：2018年3月28日 上午9:57:00   
* 联系方式：1104975916@qq.com 
*      
*/
public class ExchangerTest {
	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		final Exchanger exchanger = new Exchanger();
		service.execute(new Runnable() {//吸毒者
			public void run() {
				try {

					String data1 = "money";
					System.out.println("线程" + Thread.currentThread().getName() + "正在把数据" + data1 + "换出去");
					Thread.sleep((long) (Math.random() * 10000));
					String data2 = (String) exchanger.exchange(data1);
					System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为" + data2);
				} catch (Exception e) {

				}
			}
		});
		service.execute(new Runnable() {//毒贩
			public void run() {
				try {

					String data1 = "Heroin";
					System.out.println("线程" + Thread.currentThread().getName() + "正在把数据" + data1 + "换出去");
					Thread.sleep((long) (Math.random() * 10000));
					String data2 = (String) exchanger.exchange(data1);
					System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为" + data2);
				} catch (Exception e) {

				}
			}
		});
		service.shutdown();
	}
}
